package descentFly.away3D4.Generator
{
	import UIFree.ObjectEvent;
	
	import away3d.entities.Mesh;
	
	import descentFly.app.df_events;
	import descentFly.away3D4.df_awaySpace;
	import descentFly.away3D4.df_baseSpaceElement;
	import descentFly.away3D4.element.df_element;
	import descentFly.df_spaceObject;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	public class df_basePoints extends df_baseParser {
		public static const FIELD_TOTALCOUNT: String = 'totalCount';
		public static const FIELD_TOTALEVENT: String = 'totalEvent';
		
		private var _points		: Array;
		private var _count		: int;
		private var _totalCount	: int;
		
		public function df_basePoints(a_space:df_awaySpace, a_options:Object) {
			super(a_space, a_options);
			_count		= 0;
			_totalCount = 0;
			_points 	= new Array();
		}
		
		protected function get points(): Array {
			return _points;
		}
		
		protected function parseMesh(m: Mesh): Object {
			return {
				point	: m.transform.clone(),
				object	: null
			};
		}
		
		protected function doBeforeDisposeElem(element: df_element, pointIndex: int): void {
		}
		
		protected function createPoint(index:int): df_element {
			
			if (!this.checkTotal()) {
				var element: df_element = new (options.element.Class)(points[index].point, Space, options.element.options);
				function v_doDisposeElem(e: Event): void {
					element.removeEventListener(df_spaceObject.DISPOSE, v_doDisposeElem);
					points[index].object = null;
					doBeforeDisposeElem(element, index);
				} 
				points[index].object = element;
				element.addEventListener(df_spaceObject.DISPOSE, v_doDisposeElem);
				
				addPoint(element);
				return element;
			}
			return null;
		}
		
		override protected function parseElement(m: Mesh): void {
			points.push(parseMesh(m));
			m.dispose(true);
		}
		
		protected function checkTotal(): Boolean {
			return options.hasOwnProperty(FIELD_TOTALCOUNT) && (_totalCount >= options[FIELD_TOTALCOUNT]); 
		}
		
		protected function addPoint(point: df_spaceObject): void {
			_count++;
			_totalCount++;
			point.addEventListener(df_spaceObject.DISPOSE, doDisposePoint);
		}
		
		protected function doDisposePoint(e: Event): void {
			e.target.removeEventListener(df_spaceObject.DISPOSE, doDisposePoint);
			_count--;
			if (options.hasOwnProperty(FIELD_TOTALCOUNT) && (options[FIELD_TOTALCOUNT] <= _totalCount)) 
				doTotalEvent();
		}
		
		public function get count(): int {
			return _count;
		}
		
		protected function doTotalEvent(): void {
			if (options.hasOwnProperty(FIELD_TOTALEVENT))
				Space.dispatchEvent(new Event(options[FIELD_TOTALEVENT]));
		}
	}
}